package com.yunzai.generic.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.filter.Filter;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.nio.charset.StandardCharsets;

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        template.setHashValueSerializer(new JSONSerializer<>(Object.class));
        template.setValueSerializer(new JSONSerializer<>(Object.class));

        return template;
    }

    static class JSONSerializer<T> implements RedisSerializer<T> {

        static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter("org.springframework", "com.yunzai");

        private Class<T> clazz;

        public JSONSerializer(Class<T> clazz) {
            super();
            this.clazz = clazz;
        }

        /**
         * @param value
         * @return
         * @throws SerializationException
         */
        @Override
        public byte[] serialize(T value) throws SerializationException {
            return JSON.toJSONString(value).getBytes(StandardCharsets.UTF_8);
        }

        /**
         * @param bytes
         * @return
         * @throws SerializationException
         */
        @Override
        public T deserialize(byte[] bytes) throws SerializationException {

            if (bytes == null || bytes.length <= 0)
            {
                return null;
            }
            String str = new String(bytes, StandardCharsets.UTF_8);
            return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER);
        }
    }
}
